package cj.web.admin.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;


import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


/**
 * 利用开源组件POI3.5动态导出EXCEL文档
 * 
 * @author 何嘉
 * @version v1.0
 * @param <T>
 *            应用泛型，代表任意一个符合javabean风格的类
 */
public class ExportExcel<T>
{
	public void exportExcel(String title, String[] headers,
			Collection<T> dataset, OutputStream out){
		exportExcel(title, headers, dataset, out, "yyyy-MM-dd");
	}

	/**
	 * 这是一个通用的方法，利用了JAVA的反射机制，可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
	 * 
	 * @param title
	 *            表格标题名
	 * @param headers
	 *            表格属性列名数组
	 * @param dataset
	 *            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。
	 * @param out
	 *            与输出设备关联的流对象，可以将EXCEL文档导出到本地文件或者网络中
	 * @param pattern
	 *            如果有时间数据，设定输出格式。默认为"yyy-MM-dd"
	 */
	@SuppressWarnings("unchecked")
	public void exportExcel(String title, String[] headers,
			Collection<T> dataset, OutputStream out, String pattern)
	{
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);

		// 产生表格标题行
		HSSFRow row = sheet.createRow(0);
		for (int i = 0; i < headers.length; i++)
		{
			HSSFCell cell = row.createCell(i);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}

		// 遍历集合数据，产生数据行
		Iterator<T> it = dataset.iterator();
		int index = 0;
		while (it.hasNext())
		{
			index++;
			row = sheet.createRow(index);
			T t = (T) it.next();

			Field[] fields = t.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++)
			{
				HSSFCell cell = row.createCell(i);
				Field field = fields[i];
				String fieldName = field.getName();
				String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
				try
				{
					Class tCls = t.getClass();
					Method getMethod = tCls.getMethod(getMethodName,new Class[]{});
					if (getMethod != null) {
						Object value = getMethod.invoke(t, new Object[] {});
						String textValue = null;
						if (value == null) {
							textValue = "";
						} else if (value instanceof Date) {
							Date date = (Date) value;
							SimpleDateFormat sdf = new SimpleDateFormat(pattern);
							textValue = sdf.format(date);
						} else {
							textValue = value.toString();
						}
						if (textValue != null) {
							HSSFRichTextString richString = new HSSFRichTextString(
									textValue);
							cell.setCellValue(richString);
						}
					}
				}
				catch (Exception e){
					e.printStackTrace();
				}
			}
		}
		try{
			workbook.write(out);
		}
		catch (IOException e){
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public void exportExcel(String title, String[] headers, String[] fields, 
			List<Map> dataset, OutputStream out, String pattern)
	{
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);

		// 产生表格标题行
		HSSFRow row = sheet.createRow(0);
		for (int i = 0; i < headers.length; i++)
		{
			HSSFCell cell = row.createCell(i);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}

		// 遍历集合数据，产生数据行
		for(int i = 0; i < dataset.size(); i++){
			row = sheet.createRow(i + 1);
			Map map = dataset.get(i);
			for (int j = 0; j < fields.length; j++) {
				HSSFCell cell = row.createCell(j);
				Object obj = map.get(fields[j]);
				try {
					String textValue = null;
					if (obj == null) {
						textValue = "";
					} else if (obj instanceof Date) {
						Date date = (Date) obj;
						SimpleDateFormat sdf = new SimpleDateFormat(pattern);
						textValue = sdf.format(date);
					} else {
						textValue = obj.toString();
					}
					if (textValue != null) {
						HSSFRichTextString richString = new HSSFRichTextString(textValue);
						cell.setCellValue(richString);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		try{
			workbook.write(out);
		}
		catch (IOException e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 导出的单元格全部是string文本类型，用于生成导入模板
	 * @param title
	 * @param headers
	 * @param fields
	 * @param dataset
	 * @param out
	 * @param pattern
	 */
	@SuppressWarnings("unchecked")
	public void exportExcelWithStrCellStyle(String title, String[] headers, String[] fields, 
			List<Map> dataset, OutputStream out, String pattern)
	{
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);
		//设置单元格为文本
		HSSFCellStyle strCellStyle = workbook.createCellStyle();  
        HSSFDataFormat format = workbook.createDataFormat();  
        strCellStyle.setDataFormat(format.getFormat("@"));  

		// 产生表格标题行
		HSSFRow row = sheet.createRow(0);
		for (int i = 0; i < headers.length; i++)
		{
			HSSFCell cell = row.createCell(i);
			cell.setCellStyle(strCellStyle); 
			cell.setCellValue(headers[i]);
		}

		// 遍历集合数据，产生数据行
		for(int i = 0; i < dataset.size(); i++){
			row = sheet.createRow(i + 1);
			Map map = dataset.get(i);
			for (int j = 0; j < fields.length; j++) {
				HSSFCell cell = row.createCell(j);
				Object obj = map.get(fields[j]);
				try {
					String textValue = null;
					if (obj == null) {
						textValue = "";
					} else if (obj instanceof Date) {
						Date date = (Date) obj;
						SimpleDateFormat sdf = new SimpleDateFormat(pattern);
						textValue = sdf.format(date);
					} else {
						textValue = obj.toString();
					}
					if (textValue != null) {
						cell.setCellStyle(strCellStyle); 
						cell.setCellValue(textValue);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		try{
			workbook.write(out);
		}
		catch (IOException e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 多工作sheet方式导出
	 * @param workbook
	 * @param title
	 * @param headers
	 * @param fields
	 * @param dataset
	 * @param pattern
	 */
	@SuppressWarnings("unchecked")
	public void exportExcelMore(HSSFWorkbook workbook,String title, String[] headers, String[] fields,
			List<Map> dataset, String pattern) {

		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);

		// 产生表格标题行
		HSSFRow row = sheet.createRow(0);
		for (int i = 0; i < headers.length; i++) {
			HSSFCell cell = row.createCell(i);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}

		// 遍历集合数据，产生数据行
		for (int i = 0; i < dataset.size(); i++) {
			row = sheet.createRow(i + 1);
			Map map = dataset.get(i);
			for (int j = 0; j < fields.length; j++) {
				HSSFCell cell = row.createCell(j);
				Object obj = map.get(fields[j]);
				try {
					String textValue = null;
					if (obj == null) {
						textValue = "";
					} else if (obj instanceof Date) {
						Date date = (Date) obj;
						SimpleDateFormat sdf = new SimpleDateFormat(pattern);
						textValue = sdf.format(date);
					} else {
						textValue = obj.toString();
					}
					if (textValue != null) {
						HSSFRichTextString richString = new HSSFRichTextString(
								textValue);
						cell.setCellValue(richString);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

}
